<?php

namespace App\Models\Common;

use App\Http\Traits\UsesUuid; use WeSoonNet\LaravelPlus\Traits\Timezone;
use App\Services\Com\LogService;
use Illuminate\Database\Eloquent\Model;
use GoldSpecDigital\LaravelEloquentUUID\Database\Eloquent\Uuid;

class Dict extends Model
{
    use Uuid, UsesUuid, Timezone;

    protected $table        = 'com_dicts';
    protected $guarded      = ['created_at', 'updated_at'];
    protected $hidden       = ['pivot'];
    public    $incrementing = false;
    protected $casts        = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'deleted_at' => 'datetime:Y-m-d H:i:s',
    ];

    public static function boot()
    {
        parent::boot();

        static::created(function ($model)
        {
            LogService::write('C', true, '创建字典', json_encode($model->attributes));
        });

        static::updated(function ($model)
        {
            // 对比更改
            $original = $model->getOriginal();
            $changes  = [];
            foreach ($model->getChanges() as $key => $value)
            {
                $changes[$key] = [
                    'old' => $original[$key],
                    'new' => $value,
                ];
            }
            LogService::write('U', true, '修改字典', json_encode($changes));
        });

        static::deleted(function ($model)
        {
            LogService::write('D', true, '删除字典', json_encode($model->attributes));
        });
    }

    public function type()
    {
        return $this->belongsTo(DictType::class, 'type_id', 'id');
    }
}
